import React from 'react'
import ReactMarkdown from 'react-markdown'
import styles from './index.module.less'
import CodeBlock from './CodeBlock'
import TurndownService from 'turndown'

function MarkdownViewer({ markdownContent = '' }) {
  // 对代码的缩进进行格式化
  function formatCodeString(codeString, indentSize = 4) {
    let formattedCode = ''
    let indentLevel = 0

    const lines = codeString.trim().split('\n')

    lines.forEach((line) => {
      const trimmedLine = line.trim()

      if (trimmedLine.startsWith('}')) {
        indentLevel--
        let temp = indentLevel - 1
        if (temp <= 0) temp = 0
        formattedCode += ' '.repeat(indentSize * temp) + line + '\n'
      } else {
        formattedCode += ' '.repeat(indentSize * indentLevel) + line + '\n'
      }

      if (trimmedLine.endsWith('{')) indentLevel++
    })

    return formattedCode.trim()
  }

  const turndownService = new TurndownService()

  const format = () => {
    const s = turndownService.turndown(markdownContent.replace(/<br\/>/g, '\n'))
    return formatCodeString(s)
    // return s
  }

  const showContent = format()
  // console.log(showContent)

  return (
    <div className={styles.markdown}>
      <ReactMarkdown
        children={showContent}
        linkTarget='_blank'
        className={styles.markdown_body}
        components={{ code: CodeBlock }}
      />
    </div>
  )
}

import ErrorBoundary from '@/components/ErrorBoundary'
const sourceComponent = 'MarkdownViewer'
const MarkdownViewerEB = ErrorBoundary(MarkdownViewer, sourceComponent)
export default MarkdownViewerEB
